import streamlit as st
import random
import pandas as pd
import json

if "needReturn" not in st.session_state:
    st.session_state.needReturn = False

data = None
# 打开并读取JSON文件
with open('state/1.json', 'r', encoding='utf-8') as file:
    str = file.read()
    if str is None or str == '':
        str = "{}"
    data = json.loads(str)
    print("读取成功")

if "playerList" not in data:
    data["playerList"] = []

if "initiativeRoll" not in st.session_state:
    st.session_state.initiativeRoll = 0

playerList = data["playerList"]


def addPlayer(name, dexModifier, initiativeRoll):
    if name is None or name == "":
        st.toast("角色名称不可为空")
        return

    p = [d for d in playerList if d['name'] == name]
    if len(p) > 0:
        st.toast("角色名称已存在")
        return

    if initiativeRoll == 0:
        initiativeRoll = random.randint(1, 20)

    playerList.append(
        {"name": name, "dexModifier": dexModifier, "initiativeRoll": initiativeRoll,
         "initiative": initiativeRoll + dexModifier})


with st.form("player_form"):
    name = st.text_input("角色名称")
    dexModifier = st.number_input("敏捷属性调整值", min_value=0, max_value=100, step=1)

    left, middle, right = st.columns(3)

    if middle.form_submit_button("先攻掷骰", use_container_width=True):
        rollNum = random.randint(1, 20)
        st.toast(f"1d20 = {rollNum}")
        st.session_state.initiativeRoll = rollNum
    if right.form_submit_button("优势先攻掷骰", use_container_width=True):
        i1 = random.randint(1, 20)
        st.toast(f"1d20 = {i1}")
        i2 = random.randint(1, 20)
        st.toast(f"1d20 = {i2}")
        st.session_state.initiativeRoll = max(i1, i2)
        print(st.session_state.initiativeRoll)

    left.number_input("先攻值roll点(为0时自动掷骰)", min_value=0, max_value=20,
                      step=1,
                      value=st.session_state.initiativeRoll)

    submitted = st.form_submit_button("添加新角色", type="primary")
    if submitted:
        addPlayer(name, dexModifier, st.session_state.initiativeRoll)

playerList = sorted(playerList, key=lambda player: player["initiative"], reverse=True)


# for idx, player in enumerate(playerList):
#     col1, col2 = st.columns([3, 10])
#     col1.button(player["name"], key="player" + str(idx))
#     col2.write(
#         f"{player["name"]} ———— 先攻掷骰 {player["initiativeRoll"]} + 敏捷属性调整值 {player["dexModifier"]} = 先攻值 {player['initiative']}")

def handle_data_edit():
    for key in st.session_state.ed["edited_rows"].keys():
        print(st.session_state.ed["edited_rows"])
        if ("dexModifier" in st.session_state.ed["edited_rows"][key] or
                "initiativeRoll" in st.session_state.ed["edited_rows"][key]):
            st.session_state.needReturn = True


if len(playerList) > 0:
    df = pd.DataFrame(playerList)
    df = st.data_editor(df, disabled=["initiative"], on_change=handle_data_edit, key='ed')
    df['initiative'] = df.apply(lambda row: row["initiativeRoll"] + row["dexModifier"], axis=1)
    playerList = df.to_dict(orient='records')

data["playerList"] = playerList

with open('state/1.json', 'w', encoding='utf-8') as file:
    file.write(json.dumps(data))
    file.flush()

if st.session_state.needReturn:
    st.session_state.needReturn = False
    print("rerun")
    st.rerun()
